/**
 * @author harry
 * @date 2022/3/5/20:55
 */

package com.serviceOrchestration.atomic.units;

import com.serviceOrchestration.annotation.AtomicParam;
import com.serviceOrchestration.annotation.AtomicService;
import com.serviceOrchestration.factory.AtomicFactory;
import com.serviceOrchestration.atomic.AtomicUnitContext;
import com.serviceOrchestration.pojo.User;
import com.serviceOrchestration.atomic.AtomicUnit;
import com.serviceOrchestration.util.InputType;
import lombok.Getter;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@AtomicService(
        value = AtomicFactory.BEAN_PREFIX + 6,
        name = "用户标签控制服务",
        description = "用户类型限制。具有一定类型标签的用户才能够购买"
)
@Getter
public class UserLabelUnit extends AtomicUnit {
    @AtomicParam(
            zhName = "允许的标签",
            enName = "labelAllowed",
            type = InputType.MULTI_SELECTION,
            repository = "labelDao.selectAll"
    )
    private final Set<String> labelAllowed = new HashSet<>();

    @SuppressWarnings("unchecked")
    @Override
    public void setParams(Map<String, Object> params) throws IllegalArgumentException {
        if(params == null) {
            throw new IllegalArgumentException("the params of UserLabelUnit is null");
        }
        List<String> labels = (List<String>) params.get("labelAllowed");
        if(labels == null || labels.size() == 0) {
            throw new IllegalArgumentException("no param named 'labelAllowed'");
        }
        labelAllowed.addAll(labels);
    }

    @Override
    protected boolean doHandle(AtomicUnitContext context) {
        User user = (User) context.getContext("user");
        if (!labelAllowed.contains(user.getLabel())) {
            context.setError("用户类型不符合");
            return false;
        }
        return true;
    }
}
